import pandas as pd
from pandas import DataFrame
import sys
import os
import time
import skuDic   #加载特殊SKU代码的字典
import globalvar as gl
from parseSKUCode import parseColorSizeCode

# 获取当前路径的函数
def script_path():
    path = os.path.realpath(sys.path[0])
    if os.path.isfile(path):
        path = os.path.basename(path)
    return os.path.abspath(path)

# 创建数据帧，用于装载、整理数据
data = pd.DataFrame()

#遍历读取目录下的xlsx文件并按行合并
ori_dir = ''
if len(sys.argv)!=2:
    ori_dir = os.path.join(script_path(), "data")
    print(f"使用默认目标路径：{ori_dir}\n")
else:
    ori_dir = sys.argv[1]
if not os.path.isdir(ori_dir):
    print(f"目标参数不是文件夹. dir={ori_dir}")
    exit()

flist = os.listdir(ori_dir)
for f in flist:
    print(f'process {f}')
    path = os.path.join(ori_dir, f)
    file_ext = f.rsplit('.',maxsplit=1)

    if len(file_ext)!=2:
        continue
    if file_ext[1]!='xls' and file_ext[1]!='xlsx':
        continue

    #分文件清洗数据
    data_t = pd.read_excel(path)
    #列名不区分大小写
    data_t.columns = [x.lower() for x in data_t.columns]  # 全转换为小写
    #清洗数据
    igList = gl.get_value('ignore_sku_dic')
    data_t = data_t[~data_t['sku'].isin(igList)]   #去除不要的
    #转换
    crDic = gl.get_value('reflect_sku_dic')
    data_t['sku'] = data_t['sku'].apply(lambda x:crDic[x] if x in crDic else x )

    if not data.empty:
    	data = pd.concat([data, data_t])
    else:
    	data = data_t

#拆分
data = data.assign(LocalSKU=data['sku'].apply(parseColorSizeCode))
data = data.assign(SPU=data['LocalSKU'].apply(lambda x:x[1]),Color=data['LocalSKU'].apply(lambda x:x[2]), Size=data['LocalSKU'].apply(lambda x:x[3]),LocalSKU=data['LocalSKU'].apply(lambda x:x[0]))

#今天日期字符串
today = time.strftime("%Y%m%d",time.localtime())

data.to_excel(os.path.join(ori_dir,'订单统计-'+today+'.xlsx'), index=False)
print(data)